package cn.bld.controller;

import cn.bld.entity.SysUser;
import cn.bld.service.SysRoleService;
import cn.bld.service.SysUserService;
import cn.bld.utils.MyFileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.mysql.jdbc.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/user")
public class SysUserController extends BaseController{
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @RequestMapping ("/login")
    public String login(String account , String password , HttpSession session){
        SysUser login = sysUserService.login(account, password);
        if(null!=login){
            session.setAttribute("userSession",login);
            return "frame";
        }
        return "redirect:login";
    }
    @RequestMapping ("/show")
    public String show(HttpSession session){
        List<SysUser> show = sysUserService.show();
        if(null!=show){
            session.setAttribute("userList",show);
            return "sysUser/list";
        }
        return "redirect:frame";
    }
    @GetMapping("page")
    public  String page(@RequestParam(value = "queryRealName" ,required = false, defaultValue = "") String queryRealName,
                        @RequestParam(value = "queryRoleId",required = false,defaultValue = "0")Integer queryRoleId,
                        @RequestParam(value = "pageIndex",required = false,defaultValue = "1")Integer pageIndex,Model model){
        Integer size = 8;
        int totalCount = sysUserService.findCount(queryRealName,queryRoleId);
        int totalPageCount = totalCount%size==0?totalCount/size:totalCount/size+1;
        List<SysUser> userList = sysUserService.findByCondition(queryRealName, queryRoleId, pageIndex, size);

        model.addAttribute("totalCount",totalCount);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("currentPageNo",pageIndex);
        model.addAttribute("roleList",sysRoleService.findall());
        model.addAttribute("userList",userList);
        model.addAttribute("queryRealName",queryRealName);
        model.addAttribute("queryRoleId",queryRoleId);

        return "sysUser/list";
    }
    @GetMapping("del")
    public String del(@RequestParam("id") int id,Model model){
        int i = sysUserService.delById(id);
        if(i!=0){
            return "sysUser/list";
        }
        return "redirect:frame";
    }
    @GetMapping("/add")
    public String add(){
        return "sysUser/add";
    }
    @GetMapping("/userExist")
    @ResponseBody
    public String checkAccount(String account){
        int i = 1;
        Map<String,Object>map = new HashMap<>();
        try{
            if (StringUtils.isNullOrEmpty(account)){
                map.put("exist",-1);
                map.put("msg","用户名不能为空");
                return JSON.toJSONString(map);
            }
            i = sysUserService.checkAccount(account);
            if (i==0){
                map.put("exist",0);
            }else {
                map.put("exist",1);
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("exist",-1);
            map.put("msg","服务器访问异常，请稍后重试");
        }
        return JSON.toJSONString(map);
    }
    @PostMapping("toAdd")
    public String addUser(SysUser sysUser, MultipartFile idPics,MultipartFile workPics,HttpSession session) throws IOException {
        String path =session.getServletContext().getRealPath("upload");
        if(!idPics.isEmpty()){
            String newFilename = MyFileUtil.uploadFile(idPics, path);
            sysUser.setIdPic("upload/"+newFilename);
        }
        if (!workPics.isEmpty()){
            String newFilename = MyFileUtil.uploadFile(workPics, path);
            sysUser.setWordPic("upload/"+newFilename);
        }
        SysUser loginUser = (SysUser) session.getAttribute("userSession");
        sysUser.setCreatedUserId(loginUser.getId());
        int i = sysUserService.insertUser(sysUser);
        if (i==1){
            return "redirect:/user/page";
        }
        return "redirect:/WEB-INF/jsp/sysUser/add.jsp";
    }
    @GetMapping("/view/{opr}/{id}")
    public String view(@PathVariable Integer id,Model model,@PathVariable String opr){
        model.addAttribute(("sysUser"),sysUserService.findGyId(id));
        if("v".equals(opr)){
            return "/sysUser/view";
        }else {
            return "/sysUser/update";
        }

    }
    @GetMapping(value = "/view",produces = {"application/json;charset=UTF-8"})
    @ResponseBody//异步请求返回的是数据
    public String viewUser(Integer id ){
        SysUser gyId = sysUserService.findGyId(id);
        gyId.setSysRole(sysRoleService.findById(gyId.getRoleId()));
        JSON.DEFFAULT_DATE_FORMAT="yyyy-MM-dd";
        return JSON.toJSONString(gyId, SerializerFeature.WriteDateUseDateFormat);
    }


    @RequestMapping ("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return  "redirect:/login.jsp";
    }
    @PostMapping("update")
    public String update(SysUser sysUser,HttpSession session){
       SysUser loginUser = (SysUser) session.getAttribute("userSession");
        sysUser.setUpdatedUserId(loginUser.getId());
        int i = sysUserService.updateUser(sysUser);
        return "redirect:/user/page";
    }
    @DeleteMapping("del/{userid}")
    @ResponseBody
    public String del(@PathVariable Integer userid){
        Map<String,Object> map = new HashMap<>();
        if (sysUserService.findGyId(userid)==null){
            map.put("delResult","notexist");
            return JSON.toJSONString(map);
        }
        int i = sysUserService.deleteUser(userid);
        if (i==1){
            map.put("delResult","true");
        }else {
            map.put("delResult","false");
        }
        return JSON.toJSONString(map);
    }
//    测试spring标签以及校验
    @GetMapping("/useradd.html")
    public  String toadd(@ModelAttribute("sysUser") SysUser sysUser){
        return "sysUser/add2";
    }
    @PostMapping("/useradd.html")
    public String save(@Valid SysUser sysUser, BindingResult result){
        System.out.println(sysUser);
        if(result.hasErrors()){
            return "sysUser/add2";
        }
        return "redirect:/user/page";
    }
    @PostMapping("/checkOldPwd")
    @ResponseBody
    public String checkPassword(SysUser sysUser,HttpSession session,String oldPassword , Integer id){
        int i = 1;
        Map<String,Object>map = new HashMap<>();
        try{
            if (StringUtils.isNullOrEmpty(oldPassword)){
                map.put("result",-1);
                map.put("msg","用户名不能为空");
                return JSON.toJSONString(map);
            }
            SysUser loginUser = (SysUser) session.getAttribute("userSession");
            id = loginUser.getId();
            i = sysUserService.checkPassowrd(oldPassword,id);
            if (i==1){
                map.put("result","true");
            }else {
                map.put("result","false");
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("exist",-1);
            map.put("result","服务器访问异常，请稍后重试");
        }
        return JSON.toJSONString(map);
    }
    @GetMapping("/toUpdate")
    public String toUpdate(){
        return "sysUser/updatePassword";
    }

    @PostMapping("updatePwd")
    public String updatePwd(SysUser sysUser,HttpSession session,@RequestParam(value = "newpassword" ,required = false, defaultValue = "") String newpassword){
        SysUser loginUser = (SysUser) session.getAttribute("userSession");
        int i = sysUserService.updatePassword(loginUser.getId(),newpassword);
        return "redirect:/user/page";
    }

}
